import color from '../config/color.js'

/**
 * 获取图片主题色
 */
export const getImageThemeColor = ({ canvasId = "canvas", path }) => {
	return new Promise((resolve, reject) => {
		// Get the image file extension
		const suffix = path.split(".").slice(-1)[0];

		// Request the image as an array buffer
		uni.request({
			url: path,
			responseType: "arraybuffer",
			success: (res) => {
				let base64 = uni.arrayBufferToBase64(res.data);
				const img = {
					path: `data:image/${suffix};base64,${base64}`,
				};

				// Create a canvas context
				const ctx = uni.createCanvasContext(canvasId);

				// Image drawing dimensions
				const imgWidth = 2;
				const imgHeight = 2;

				// Draw the image on the canvas
				ctx.drawImage(img.path, 0, 0, imgWidth, imgHeight);
				ctx.save();
				ctx.draw(true, () => {
					// Get the image data from the canvas
					uni.canvasGetImageData({
						canvasId,
						x: 0,
						y: 0,
						width: imgWidth,
						height: imgHeight,
						success: (res) => {
							let data = res.data;
							let r = 0,
								g = 0,
								b = 0;

							// Sum all pixel values
							for (let i = 0; i < data.length; i += 4) {
								r += data[i];
								g += data[i + 1];
								b += data[i + 2];
							}

							// Calculate the average values
							const pixelCount = data.length / 4;
							r = Math.round(r / pixelCount);
							g = Math.round(g / pixelCount);
							b = Math.round(b / pixelCount);

							// Resolve the average RGB color
							resolve(`rgb(${r},${g},${b})`);
						},
						fail: (error) => {
							reject(error);
						}
					});
				});
			},
			fail: (error) => {
				reject(error);
			}
		});
	});
}


/**
 * rpx转px
 * @param {number}  rpx
 */
export const rpx2px = (rpx) => {
	return rpx / 750 * uni.getWindowInfo().windowWidth
}

/**
 * px转rpx
 * @param {number} px
 */
export const px2rpx = (px) => {
	return (px * 750) / uni.getWindowInfo().windowWidth
}

/**
 * 判断是否微信环境
 * @returns {boolean} 返回Boolean
 */
export const isWechat = () => {
	const ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') return true;
	else return false;
}

/**
 * 判断是否企业微信环境
 * @returns {boolean} 返回Boolean
 */
export const isWxWork = () => {
	const ua = window.navigator.userAgent.toLowerCase();
	if ((ua.match(/MicroMessenger/i) == 'micromessenger') && (ua.match(/wxwork/i) == 'wxwork')) return true;
	else return false;
}

/**
 * @description 进行延时，以达到可以简写代码的目的 比如: await uni.$u.sleep(20)将会阻塞20ms
 * @param {number} value 堵塞时间 单位ms 毫秒
 * @returns {Promise} 返回promise
 */
export const sleep = (value = 30) => {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve()
		}, value)
	})
}

/**
 * 判断是否为空
 * @param {any}  val 参数
 */
export const isEmpty = (val) => {
	return !(!!val ? typeof val === 'object' ? Array.isArray(val) ? !!val.length : !!Object.keys(val).length : true : false);
}

/**
 * 替换符号
 * @param {string}	value 要替换的参数
 * @param {Array}  symbolList 要替换的符号列表  
 */
export const replaceSymbol = (value, symbolList) => {
	let result = value
	symbolList.forEach(item => {
		result = result.replace(item, '')
	})
	return result
}

/**
 * 显示toast消息
 * @param {Object} options 选项对象
 * @param {string} options.title 消息标题
 * @param {string} [options.icon='none'] 图标类型，默认为'none'
 * @param {boolean} [options.mask=true] 是否显示透明蒙层，默认为true
 * @param {number} [options.duration=2000] 显示时长（毫秒），默认为2000
 * @returns {Promise<any>} 返回一个Promise，当toast显示成功时解析，显示失败时拒绝
 */
export const showToast = ({
	title,
	icon = 'none',
	mask = true,
	duration = 2000,
}) => {
	return new Promise((resolve, reject) => {
		uni.showToast({
			title,
			icon,
			mask,
			duration,
			success: (res) => {
				resolve(res)
			},
			fail: (error) => {
				reject(error)
			}
		})
	})
}

/**
 * 隐藏消息框
 */
export const hideToast = () => {
	uni.hideToast()
}

/**
 * 显示模态弹窗
 * @tutorial http://uniapp.dcloud.io/api/ui/prompt?id=showmodal 
 */
export const showModal = ({
	title = '提示',
	content = '',
	showCancel = true,
	cancelText = '取消',
	cancelColor = '#000000',
	confirmText = '确定',
	confirmColor = color.primary
}) => {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title,
			content,
			showCancel,
			cancelText,
			cancelColor,
			confirmText,
			confirmColor,
			success: (res) => {
				resolve(res)
			},
			fail: (error) => {
				reject(error)
			}
		})
	})
}

/**
 * 显示操作菜单
 * @param { array } itemList 按钮的文字数组
 * @tutorial http://uniapp.dcloud.io/api/ui/prompt?id=showactionsheet 
 */
export const showActionSheet = (itemList) => {
	return new Promise((resolve, reject) => {
		uni.showActionSheet({
			itemList: itemList,
			success: (res) => {
				resolve(res)
			},
			fail: (error) => {
				if (error.errMsg !== "showActionSheet:fail cancel") {
					reject(error)
				}
			}
		})
	})
}

/**
 * 显示 loading 提示框
 * @tutorial http://uniapp.dcloud.io/api/ui/prompt?id=showloading
 */
export const showLoading = (title) => {
	uni.showLoading({
		title: title ? title : '加载中...',
		mask: true
	})
}

/**
 * 隐藏 loading 提示框
 * @tutorial http://uniapp.dcloud.io/api/ui/prompt?id=hideloading 
 */
export const hideLoading = () => {
	uni.hideLoading()
}

export default {
	rpx2px,
	px2rpx,
	sleep,
	isEmpty,
	isWechat,
	isWxWork,
	replaceSymbol,
	showToast,
	hideToast,
	showModal,
	showActionSheet,
	showLoading,
	hideLoading,
	getImageThemeColor,
}